import axios, {
  InternalAxiosRequestConfig,
  AxiosError,
  AxiosResponse,
} from "axios";

import { uMsg } from "@/store/vMessage";


axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_API;

// 请求拦截器
axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers.Authorization = "Bearer " + localStorage.getItem("token");
    return Promise.resolve(config);
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use((response: AxiosResponse) => {
  return response;
});

enum SEND_TYPE {
  GET = "get",
  POST = "post",
}

// 请求响应配置
export const https = async <T, R>(method: SEND_TYPE, url: string, data?: R) => {
  return new Promise<T>((resolve, reject) => {
    let param;

    if (method === SEND_TYPE.POST) {
      param = { data: data };
    } else {
      param = { params: data };
    }

    axios({
      method: method,
      url: url,
      ...param,
    })
      .then((res) => {
        if (res.status === 200) {
          // 请求成功
          if (res.data.code === 2) {
            const vMsg = uMsg();
            res.data.msg !== null && vMsg.Open(res.data.msg);
            // 服务器响应2
            resolve(res.data.data);
          }
          if (res.data.code === 1) {
            const vMsg = uMsg();
            // 服务器响应500错误
            res.data.data!== null && vMsg.Open(res.data.data);
            reject(res.data.data);
          }
        } else {
          // 请求失败
          reject(res.data.msg);
        }
      })
      .catch((err) => {
        // 发送请求失败，没有建立连接
        reject(err);
      });
  });
};

// get请求
export const _Get = async <T, R>(url: string, params: R) => {
  return await https<T, R>(SEND_TYPE.GET, url, params);
};

export const _Post = async <T, R>(url: string, data: R) => {
  return await https<T, R>(SEND_TYPE.POST, url, data);
};
